iT邦幫忙

0

Day 10: 125. Valid Palindrome

  • 分享至 

  • xImage
  •  

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
解題思路
1.判斷字串是否為回文,但只考慮英文字母和數字,忽略大小寫與符號。
2.解法概念:雙指標
一個指標left從左邊開始。
一個指標right從右邊開始。
當遇到非字母或數字時就跳過。
比較兩端字元是否相同。
3.結束條件:
當左右指標交錯時仍未發現不匹配,就代表是回文。
https://ithelp.ithome.com.tw/upload/images/20251014/201794248ISIYDLwQY.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言